<?php
/**
 * Json decorator class for Alinks_Form
 *
 * Used to get a Json string from a form, rather than HTML. This
 * is specifically meant to be used on the keyphrases page, where
 * the forms are all Ajax based.
 *
 * Copyright (C) 2008  Sean Hickey
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Sean Hickey <sean@headzoo.com>
 * @verion $Id: Json.php 389 2008-07-03 05:37:28Z sean $
 * @package Alinks_Form
 */
class Alinks_Form_Json
{
	/**
	 * Instance of Alinks_Form
	 *
	 * @var Alinks_Form
	 */
	protected $_form;
	
	/**
	 * Constructor
	 *
	 * @param Alinks_Form $form The form to decorate
	 */
	public function __construct(Alinks_Form $form)
	{
		$this->_form = $form;
	}
	
	/**
	 * Returns the form as a Json encoded string
	 *
	 * @return string
	 */
	public function getJson()
	{
		$obj = new stdClass();
		foreach($this->_form->getElements() as $element) {
			$name = $element->getName();
			$obj->$name = new stdClass();
			$obj->$name->id 			= $element->getId();
			$obj->$name->value 		= $element->getValue();
			$obj->$name->label 		= $element->getRawLabel();
			$obj->$name->description 	= $element->getDescription();
			$obj->$name->args 		= $this->_arrayToStdClass($element->getArgs());
			$obj->$name->required 	= $element->isRequired();
			$obj->$name->must_match 	= $element->getMustMatch();
			$obj->$name->not_match 	= $element->getNotMatch();
			$obj->$name->must_match_msg	= $element->getMustMatchMessage();
			$obj->$name->not_match_msg = $element->getNotMatchMessage();
			$obj->$name->required_msg = $element->getRequiredMessage();
			$obj->$name->type			= get_class($element);
			if ($element instanceof Alinks_Form_Element_Select) {
				$obj->$name->options = $this->_arrayToStdClass($element->getOptions());
			}
		}
		
		return json_encode($obj);
	}
	
	/**
	 * Returns the form Json string
	 *
	 * @return string
	 */
	public function __toString()
	{
		return $this->getJson();
	}
	
	/**
	 * Converts an array into a stdClass instance
	 *
	 * @param array $args The array to convert
	 * @return stdClass
	 */
	protected function _arrayToStdClass(array $args)
	{
		$c = new stdClass();
		foreach($args as $key => $value) {
			$c->$key = $value;
		}
		
		return $c;
	}
}